package tech.wangpai.microservice.order;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class ServiceCall {
    @Value("${zookeeper.address}")
    private String zkAddress;

    public void test() throws Exception {
        CuratorFramework client = CuratorFrameworkFactory.newClient(zkAddress, new RetryOneTime(1000));
        client.start();
        client.blockUntilConnected();

        ServiceDiscovery<Object> serviceDiscovery = ServiceDiscoveryBuilder.builder(Object.class).client(client).basePath("/soa").build();

        Collection<ServiceInstance<Object>> list = serviceDiscovery.queryForInstances("product");

        List<String> services = new ArrayList<>();
        list.forEach((instance -> {
            services.add(instance.getAddress() + ":" + instance.getPort());
        }));
        LoadBalance loadBalance = new LoadBalance(services);
        RestTemplate restTemplate = new RestTemplate();
        String body = restTemplate.getForObject(String.format("http://%s/soa/product/1",loadBalance.choose()), String.class);
        System.out.println(body);
    }
}
